package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.domain.Client;
import com.ruoyi.system.domain.Pclient;
import com.ruoyi.system.domain.Position;
import com.ruoyi.system.domain.SysClientAss;
import com.ruoyi.system.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2023-11-01
 */
@RestController
@RequestMapping("/system/client")
public class ClientController extends BaseController
{
    @Resource
    private IClientService clientService;

    @Resource
    private IPositionService positionService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysClientAssService sysClientAssService;

    /**
     * 查询【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:client:list')")
    @GetMapping("/list")
    public TableDataInfo list(Client client)
    {
        startPage();
        //查询当前用户角色
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        if (roles != null && roles.size() > 0) {
            if (roles.contains("admin") || roles.contains("boss")) {
                client.setCidStr("");
            } else {
                //获取是否有分配任务
                SysClientAss sysClientAss = new SysClientAss();
                sysClientAss.setIsAss(1L);
                sysClientAss.setUserId(getUserId());
                List<SysClientAss> sysClientAssList = sysClientAssService.selectSysClientAssList(sysClientAss);
                String cidStr = "";
                if (sysClientAssList != null && sysClientAssList.size() > 0) {
                    List<String> cidList =
                            sysClientAssList.stream().map(item -> {
                                Long cid = item.getcId();
                                return String.valueOf(cid.longValue());
                            }).collect(Collectors.toList());
                    cidStr = String.join(",", cidList);
                }
                client.setCidStr(cidStr);
            }
        } else {
            client.setCidStr("0");
        }
        List<Client> list = clientService.selectClientList(client);
        if (list != null && list.size() > 0) {
            SysUser sysUser = sysUserService.selectUserById(getUserId());
            if (sysUser == null) {
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(20001);
                rspData.setMsg("用户不存在");
                return rspData;
            }
            for (int i = 0; i < list.size(); i++) {
                //获取该公司所有招聘的职位
                Position position = new Position();
                position.setClientId(list.get(i).getId());
                List<Position> positionList = positionService.selectPositionList(position);
                if (positionList != null && positionList.size() > 0) {
                    list.get(i).setPoSize(positionList.size());
                } else {
                    list.get(i).setPoSize(0);
                }
                //添加分配历史
//                SysClientAss sysClientAss = new SysClientAss();
//                sysClientAss.setcId(list.get(i).getId());
//                List<SysClientAss> sysClientAssList = sysClientAssService.selectSysClientAssList(sysClientAss);
//                if (sysClientAssList != null && sysClientAssList.size() > 0) {
//                    for (SysClientAss ass:
//                    sysClientAssList) {
//                        SysUser sysUser1 = sysUserService.selectUserById(ass.getUserId());
//                        ass.setUserName(sysUser1.getUserName());
//                    }
//                    list.get(i).setAssList(sysClientAssList);
//                }
                list.get(i).setShortName(sysUser.getShorthand());
                String filePath = list.get(i).getFilePath();
                //需要检查的文件格式
                for (int j = 0; j < MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION.length; j++) {
                    File file = new File("/home/ruoyi/uploadPath/folder/" + "client_tc" + list.get(i).getId() + "." + MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION[j]);
                    if (file.exists()) {
                        //存在
                        if (StringUtils.isBlank(filePath)) {
                            filePath = "http://jobslink.megaslink.com/profile/folder/" + "client_tc" + list.get(i).getId() + "." + MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION[j];
                        } else {
                            filePath = filePath + "," + "http://jobslink.megaslink.com/profile/folder/" + "client_tc" + list.get(i).getId() + "." + MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION[j];
                        }
                    }
                }
                list.get(i).setFilePath(filePath);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:client:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Client client)
    {
        List<Client> list = clientService.selectClientList(client);
        ExcelUtil<Client> util = new ExcelUtil<Client>(Client.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:client:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(clientService.selectClientById(id));
    }

    @Resource
    private IPclientService pclientService;

    /**
     * 新增【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:client:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Client client)
    {
        if (!StringUtils.isBlank(client.getType()) && client.getType().equals("1")) {
            //分配而来
            //删除之前的pcliect
            Long id = client.getId();
            Pclient pclient = pclientService.selectPclientById(id);
            pclient.setDelFlag(1);
            pclientService.updatePclient(pclient);
        } else {

        }
        client.setCreateUserId(getUsername());
        client.setCreateTime(new Date());
        Long rel = clientService.insertClient(client, getUserId());
        if (rel == null) {
            return toAjax(0);
        } else {
           return success(rel);
        }
    }

    /**
     * 修改【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:client:edit')")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Client client) {

        return toAjax(clientService.updateClient(client, getUsername()));
    }

    /**
     * 删除【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:client:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(clientService.deleteClientByIds(ids));
    }
}
